package com.codegen.platform;

import com.codegen.platform.common.ColumnEntity;
import com.codegen.platform.common.TableEntity;
import com.codegen.platform.common.utils.JdbcUtils;
import com.codegen.platform.common.utils.PropertiesUtils;
import com.codegen.platform.generator.constant.GenConstant;
import com.codegen.platform.generator.utils.GenUtils;
import com.codegen.platform.generator.utils.VelocityUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.VelocityContext;

/**

 生成视图查询
 */

@SuppressWarnings({"unchecked","fallthrough"})
public class JdbcGenView {

    private  static    String jdbcDriver = "com.mysql.jdbc.Driver";
    private  static    String jdbcUrl = "jdbc:mysql://192.168.1.60:3306/vip_local_test?useUnicode=true&characterEncoding=utf-8";
    private  static    String jdbcUsername = "root";
    private  static    String jdbcPassword = "root";
    public static void main(String[] args) throws Exception {
        //模块路径
        String tablePrefix = "admin";
        //视图名称
        String  modelView="adminView";
        String javaModule = tablePrefix;
        String webModule = tablePrefix;

        String tableSql = "SELECT a.uesr_name,a.`password`,l.remark from admin as a INNER JOIN admin_act_log as l on a.id=l.admin_id ";
        //生成关联查询视图
        generatiorViewCode(tablePrefix, javaModule, webModule,modelView,tableSql);
    }
    @SuppressWarnings({"unchecked","fallthrough"})
    public  static  void  generatiorViewCode(
            String tablePrefix,
            String javaModule,
            String webModule,String modelView,String tableSql) throws Exception {
        System.out.println("生成数据视图库文件……");
        String rootPath = "";
        String osName = "os.name";
        String osWindows = "win";
        if(!System.getProperty(osName).toLowerCase().startsWith(osWindows)) {
            rootPath = "/";
        }



        JdbcUtils jdbcUtils = new JdbcUtils(jdbcDriver, jdbcUrl, jdbcUsername, jdbcPassword);
        List<Map> tableList = jdbcUtils.selectByParams(tableSql +"   LIMIT 1 ", null);
        if (tableList == null || tableList.size() ==0){
            return;
        }

        TableEntity table = new TableEntity();
        String tableName =modelView;
        String className = GenUtils.columnToJavaNoChange(tableName);
        table.setTableName(tableName);
        table.setClassName(className);
        table.setObjName(StringUtils.uncapitalize(className));
        table.setTableComment("表明备注");
        Iterator<Map> tableIterator = tableList.iterator();
        Map<String, String> currColumn = tableIterator.next();
        Set<Entry<String, String>> entrySet = currColumn.entrySet();
        ColumnEntity columnEntity = null;
        for (Entry<String, String> entry : entrySet) {
            columnEntity = new ColumnEntity();
            columnEntity.setExtra("扩展属性"); //((HashMap.Node)((HashMap)currColumn).entrySet().toArray()[0]).getValue()
            String key=entry.getKey();
            String methodName = GenUtils.columnToJava(key);
            columnEntity.setColumnName(key);
            columnEntity.setFieldName(StringUtils.uncapitalize(methodName));
            columnEntity.setMethodName(methodName);

            columnEntity.setColumnKey("");
            columnEntity.setDataType(typeOf(entry.getValue()));
            columnEntity.setColumnComment("");
            // 属性类型
            columnEntity.setFieldType(columnEntity.getDataType());
            table.addColumn(columnEntity);
        }
        List<TableEntity> tables = new ArrayList<>();
        tables.add(table);
        String projectPath = getProjectPath();
        System.out.println("===>>>java generation path:" + projectPath +"/src/main/java");
        System.out.println("===>>>web generation path:" + projectPath + "/src/main/resources/templates/view\n");
        Map<String, Object> map = null;

        for (TableEntity tableEntity : tables) {
            System.out.println("============ start table: " + tableEntity.getTableName() + " ================");
            String baseUrl=rootPath + getProjectPath() + "/src/main/java/" + PropertiesUtils.getInstance("velocity/generator").get("package").replace(".","/") + "/modules/"+tableEntity.getTableName();
            System.out.println("文件夹路径:"+baseUrl);
            //System.out.println("删除文件夹路径:"+baseUrl);
            //delFolder(baseUrl);
            // 封装模板数据
            map = new HashMap<>(16);
            map.put("tableName", tableEntity.getTableName());
            map.put("comments", tableEntity.getTableComment());
            map.put("pk", tableEntity.getPk());
            map.put("className", tableEntity.getClassName());
            map.put("objName", tableEntity.getObjName());
            map.put("functionCode", webModule);
            map.put("querysql",tableSql);
            map.put("requestMapping", tableEntity.getTableName().replace("_","/"));
            map.put("viewPath", webModule + "/" + tableEntity.getClassName().toLowerCase());
            map.put("authKey", GenUtils.urlToAuthKey(tableEntity.getTableName().replace("_","/")));
            map.put("columns", tableEntity.getColumns());
            map.put("hasDecimal", tableEntity.buildHasDecimal().getHasDecimal());
            map.put("package", PropertiesUtils.getInstance("velocity/generator").get("package"));
            map.put("module", javaModule);
            map.put("author", PropertiesUtils.getInstance("velocity/generator").get("author"));
            map.put("email", PropertiesUtils.getInstance("velocity/generator").get("email"));
            VelocityContext context = new VelocityContext(map);

            for (String template : GenUtils.getViewTemplates()) {
                String filePath = getFileName(template, javaModule, webModule, tableEntity.getClassName(), rootPath);
                String templatePath = rootPath + JdbcUtils.class.getResource("/"+template).getPath().replaceFirst("/", "");
                System.out.println(filePath);
                File dstDir = new File(VelocityUtils.getPath(filePath));
                //文件夹不存在创建文件夹
                if(!dstDir.exists()){
                    dstDir.mkdirs();
                }
                File dstFile = new File(filePath);
                //文件不存在则创建
                if(!dstFile.exists()){
                    VelocityUtils.generate(templatePath, filePath, context);
                    System.out.println(filePath + "===>>>创建成功！");
                } else {
                    System.out.println(filePath + "===>>>文件已存在，删除文件，重新生成文件！");
                    dstFile.delete();
                    VelocityUtils.generate(templatePath, filePath, context);
                    System.out.println(filePath + "===>>>文件已重新生成！");
                }
            }
            System.out.println("============ finish table: " + tableEntity.getTableName() + " ================\n");
        }
        System.out.println("数据视图库文件生成成功！");
    }

    public  static  String  typeOf(Object param){

        if (param instanceof Integer) {
            return  "Integer";
        } else if (param instanceof String) {
            return  "String";
        } else if (param instanceof Double) {
            return  "Double";
        } else if (param instanceof Float) {
            return  "Float";
        } else if (param instanceof Long) {
            return  "Long";
        } else if (param instanceof Boolean) {
            return  "Boolean";
        } else if (param instanceof Date) {
            return  "Date";
        }
        return  "Object";
    }


    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); //删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            System.out.println("删除文件夹内文件异常!");
        }
    }

    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }


    public static String getFileName(String template, String javaModule, String webModule, String className, String rootPath) {
        String packagePath = rootPath + getProjectPath() + "/src/main/java/" + PropertiesUtils.getInstance("velocity/generator").get("package").replace(".","/") + "/modules/" + javaModule + "/";
        String resourcePath = rootPath + getProjectPath() + "/src/main/resources/";
        String webPath = resourcePath + "templates/";

        if (template.contains(GenConstant.JAVA_ENTITY)) {
            return packagePath + "entity/" + className + "Entity.java";
        }
        if (template.contains(GenConstant.JAVA_ENTITY_View)) {
            return packagePath + "entity/" + className + "EntityView.java";
        }
        if (template.contains(GenConstant.JAVA_MAPPER)) {
            return packagePath + "dao/" + className + "Mapper.java";
        }

        if (template.contains(GenConstant.XML_MAPPER)) {
            return resourcePath + "mapper/" + javaModule + "/" + className + "Mapper.xml";
        }

        if (template.contains(GenConstant.JAVA_SERVICE)) {
            return packagePath + "service/" + className + "Service.java";
        }

        if (template.contains(GenConstant.JAVA_SERVICE_IMPL)) {
            return packagePath + "service/impl/" + className + "ServiceImpl.java";
        }

        if (template.contains(GenConstant.JAVA_CONTROLLER)) {
            return packagePath + "controller/" + className + "Controller.java";
        }




        return null;
    }

    public static String getProjectPath() {
        String basePath = JdbcUtils.class.getResource("/").getPath().replace("/target/classes/", "").replaceFirst("/", "");
        return basePath;
    }


}
